import asyncio
from pymodbus.server import StartAsyncTcpServer
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.exceptions import ModbusException
from pymodbus.pdu import ExceptionResponse


# 自定义数据存储，用于模拟错误响应
class CustomDataBlock(ModbusSequentialDataBlock):
    def __init__(self, address, values):
        super().__init__(address, values)

    def validate(self, address, count=1):
        # 模拟请求被破坏的情况，这里简单判断地址是否为特定值
        if address == 2:
            raise ModbusException("Broken request")
        return super().validate(address, count)

    def getValues(self, address, count=1):
        # 模拟错误响应，这里简单判断地址是否为特定值
        if address == 3:
            return ExceptionResponse(1, 1)  # 模拟错误码为 1 的异常响应
        return super().getValues(address, count)


async def run_custom_server():
    # 初始化数据存储
    store = ModbusSlaveContext(
        di=CustomDataBlock(1, [0] * 100),
        co=CustomDataBlock(1, [0] * 100),
        hr=CustomDataBlock(1, [0] * 100),
        ir=CustomDataBlock(1, [17345] * 100))
    context = ModbusServerContext(slaves=store, single=True)

    # 启动 Modbus TCP 服务器
    try:
        print("Starting Modbus server...")
        await StartAsyncTcpServer(context, address=("192.168.1.234", 502))
        
    except Exception as e:
        print(f"Error starting server: {e}")


if __name__ == "__main__":
    asyncio.run(run_custom_server())
    